import { IClientMessage } from "../../Interfaces/Sockets/IClientMessage";
import { IStore } from "../../Interfaces/IStore";
import { CryptoUtility } from "../../../Crypto/CryptoUtility";
import { StoreManager } from "../../Managers/StoreManager";



export class ClientMessage implements IClientMessage,IStore
{
    public static ClassName:string = "ClientMessage";

	public id:string = "";
    protected _bytes:ArrayBuffer;
    protected _content:any = null;

    public write(value:any,writeAction:boolean =false):void
    {
        if(typeof value !== "string")
        {
            if(!value.hasOwnProperty("id"))
                value.id = this.id;
            value = JSON.stringify(value);
        }
        this._content = value;
        this._bytes = CryptoUtility.Word2ByteArray(CryptoUtility.GetBytes(value));
        // if(writeAction)this._bytes = CryptoUtility.Word2ByteArray(CryptoUtility.GetBytes(value),true,this.action);
        // else this._bytes = CryptoUtility.Word2ByteArray(CryptoUtility.GetBytes(value));
    }
    public parser(value:any):void
    {
        if(typeof value === "string")this._content = JSON.parse(value);
        else this._content = value;

        if(this._content.hasOwnProperty("id"))
            this.id = this._content.id;
    }
    public clear():void
    {
        this._content = null;
        this.id = "";
    }
    public get bytes():ArrayBuffer{return this._bytes;}
    public get content():any{return this._content;}

    public dispose():void
    {
        this.clear();
        StoreManager.Store(this);
    }
    public static Get(action:any = null,data:any=null,writeAction:boolean =false):ClientMessage
    {
        let msg:ClientMessage = StoreManager.New(ClientMessage);
        if(action!=null)msg.id = action;
        if(data!=null)msg.write(data,writeAction);
        return msg;
    }
}
